#!/usr/bin/env python
# encoding: utf-8
"""
hrOverlap.py

Created by Theron Terhune and Brant Faircloth on 2008-02-11.
Copyright (c) 2008 Theron Terhune and Brant Faircloth. All rights reserved.

Computes home range overlap between individuals.  

Requires:  

1) a folder of individual home ranges (wspace + "indiv")
2) a shapefile containing all home ranges (wspace + "dissolve.shp")

wspace = the base folder of both the files above

we re adding a field to the output with gp.AddField_management called bird_ref,
this is because we work on birds, and bird_ref is the id of the individual to 
which the base is being compared.

"""

# Import system modules
import sys, string, os, arcgisscripting, pdb

# Create the Geoprocessor object
gp = arcgisscripting.create()

# allows you to overwrite files -- 0 is default which prevents you from overwriting files and therefore gives error msg
gp.overwriteoutput = 1

# Load required toolboxes...
gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")
gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Analysis Tools.tbx")
gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Spatial Statistics Tools.tbx")

# define the base workspace
wspace = "C:\\Documents and Settings\\bcf\\Desktop\\maps\\breedingHomeRanges\\kernel\\breeding\\dissolved\\2001\\"
# define a place for temp files (trash)
trashSpace = wspace + "NewTrash\\"

def createFolder():
    #create 2 new folders for new shapefiles created in the this script
    output_location = wspace
    output_folder = "NewTrash"
    output_location2 = trashSpace
    output_folder2 = "NewClips"
    # Process: Create Folder...
    gp.CreateFolder_management(output_location, output_folder)
    gp.refreshcatalog(output_location)
    gp.CreateFolder_management(output_location2, output_folder2)
    gp.refreshcatalog(output_location2)
    
def newFeature():   # this function creates a shapefile with all home ranges except for the individual of interest
    # create workspace -- this is the folder with the individual MCPs
    gp.workspace = wspace + "indiv"
    # base_shp is the base shapefile with all MCPs merged
    base_shp = wspace + "dissolve.shp"
    # out_ws is variable name indicating where output is to be placed
    out_ws = trashSpace
    # Get a list of the feature classes (polygons only) in the workspace
    fcs = gp.ListFeatureClasses("*","polygon")
    # Loop through the list of feature classes
    fcs.reset() # to start at the first item in the lisf of poly-feature classes in folder
    fc = fcs.next()
    while fc:
        # Process: Feature Class to Feature Class...
        # listfc is variable name splitting feature class names obtained from gp.ListFeatureClasses
        listfc = fc.split(".")
        # newfc creates variable appending the SQl syntax and individual id found in the shapefile attribute table (in this case the column is MCP_ID)
        newfc = (("Names <> '%s'") % (listfc[0]))
        # FeatureclassToFeatureclass_conversion <in_Features> <out_path> <out_name> {where_clause} {field_mapping} {config_keyword} 
        gp.FeatureClassToFeatureClass_conversion(base_shp, out_ws, fc, newfc)
        fc = fcs.next()

def newClip():
    #pdb.set_trace()
    # create workspace --- these are the individuals home range shapefiles
    gp.workspace = wspace + "indiv"
    # create workspace #2 --- these are the combined home range shapefiles created from newFeature (above; i.e. w/o individual for clipping)
    workspace2 = trashSpace
    out_ws = trashSpace + "NewClips\\"
    # Get a list of the feature classes in the workspace
    fcs = gp.ListFeatureClasses("*","polygon")
    # Loop through the list of feature classes
    fcs.reset() # to start at the first item in the lisf of poly-feature classes in folder
    fc = fcs.next()
    while fc:
        # Process: Feature Class to Feature Class...
        listfc = fc.split(".")
        newfc = (workspace2 + fc)   # assigns name to apprapriate shapefile (= shapefile w/all MCPs except individual) 
        clipname = out_ws + (('Clip_' + '%s' + '.shp') % (listfc[0])) # assigns a new name to the clip feature for each individual
        gp.Clip_analysis(newfc, fc, clipname, "")        
        fc = fcs.next()

def addField():
    # create workspace --- these are the individuals home range shapefiles
    gp.workspace = trashSpace + "NewClips\\"
    # Get a list of the feature classes in the workspace
    fcs = gp.ListFeatureClasses("*","polygon")
    # Loop through the list of feature classes
    fcs.reset() # to start at the first item in the lisf of poly-feature classes in folder
    fc = fcs.next()
    while fc:
        listfc = fc.split(".")
        newlist = listfc[0].split("_")
        BirdRef = (("'%s'") % (newlist[1]))
        gp.AddField_management(fc, "Bird_ref", "TEXT", "", "", "", "", "NON_NULLABLE", "NON_REQUIRED", "")
        gp.CalculateField_management(fc, "Bird_ref", BirdRef, "PYTHON", "")
        fc = fcs.next()

def mcpMerge():
    # create workspace --- these are the individual 'modified' (from above functions) home range
    gp.workspace = trashSpace + "NewClips\\"
    outfc = trashSpace + "NewClips\\FinalMcpMerged.shp"
    # Get a list of the feature classes in the workspace
    fcs = gp.ListFeatureClasses("*","polygon")
    # Loop through the list of feature classes
    fcs.reset() # to start at the first item in the lisf of poly-feature classes in folder
    fc = fcs.next()
    inputs = fc     # sets string variable to be insert into Merge tool below
    fc = fcs.next()
    while fc:
        inputs = inputs + ";" + fc
        fc = fcs.next()        
    gp.Merge_management(inputs, outfc)

def calcArea():
    # create workspace --- these are the individual 'modified' (from above functions) home range shapefiles
    shape = trashSpace + "NewClips\\FinalMcpMerged.shp"
    outshape = wspace + "FinalMcpMerged.shp"
    gp.CalculateAreas_stats(shape, outshape)
    outshape2 = wspace + "FinalMcpMerged.shp"
    gp.AddField_management(outshape2, "Acres", "DOUBLE", "", "", "", "", "NON_NULLABLE", "NON_REQUIRED", "")
    gp.AddField_management(outshape2, "Hectares", "DOUBLE", "", "", "", "", "NON_NULLABLE", "NON_REQUIRED", "")
    gp.CalculateField_management(outshape2, "Acres", "[F_AREA]*0.0002471054", "VB", "")
    gp.CalculateField_management(outshape2, "Hectares", "[F_AREA]*0.0001", "VB", "")

def deleteFolders():
    # delete folders and shapefiles that you created except final shapefile with individual information
    byebye = trashSpace
    gp.delete_management(byebye)


createFolder()        
newFeature()
newClip()
addField()
mcpMerge()
calcArea()
deleteFolders()
